<template>
  <div>
    <!-- <div>
      <button
        @click="openMap"
        class="custom-button"
        :style="{
          position: 'absolute',
          top: '%3',
          right: '7%',
          display: 'flex',
        }"
      >
        后台数据中心
      </button>
    </div> -->
    <div style="margin-top: 3%">
      <!-- 按钮容器，用于日、周、月、总数按钮 -->
      <div style="
          position: relative;
          width: 100%;
          height: 400px;
          margin-bottom: 5%;
        ">
        <div style="text-align: center; margin-bottom: 2px">
          <button @click="changeData('DAY', 0, 0, 0)" :class="['custom-button', { active: CheckButton1 === 0 }]">
            日活
          </button>
          <button @click="changeData('WEEK', 0, 1, 0)" :class="['custom-button', { active: CheckButton1 === 1 }]">
            周活
          </button>
          <button @click="changeData('MONTH', 0, 2, 0)" :class="['custom-button', { active: CheckButton1 === 2 }]">
            月活
          </button>
        </div>
        <div ref="chartContainer" style="width: 100%; height: 400px"></div>
      </div>

    

      <div style="
          position: relative;
          width: 100%;
          height: 400px;
          margin-bottom: 5%;
        ">
        <div style="text-align: center; margin-bottom: 2px">
          <button @click="changeData('DAY', 2, 0, 1)" :class="['custom-button', { active: CheckButton2 === 0 }]">
            日新增
          </button>
          <button @click="changeData('WEEK', 2, 1, 1)" :class="['custom-button', { active: CheckButton2 === 1 }]">
            周新增
          </button>
          <button @click="changeData('MONTH', 2, 2, 1)" :class="['custom-button', { active: CheckButton2 === 2 }]">
            月新增
          </button>
          <button @click="changeData('TOTAL', 2, 3, 1)" :class="['custom-button', { active: CheckButton2 === 3 }]">
            总数
          </button>
        </div>

        <div ref="chartContainer1" style="width: 100%; height: 400px"></div>
      </div>

        <div style="
          position: relative;
          width: 100%;
          height: 400px;
          margin-bottom: 5%;
        ">
        <div style="text-align: center; margin-bottom: 2px">
          <button @click="changeData('DAY', 1, 0, 11)" :class="['custom-button', { active: CheckButton6 === 0 }]">
            日新增
          </button>
          <button @click="changeData('WEEK', 1, 1, 11)" :class="['custom-button', { active: CheckButton6 === 1}]">
            周新增
          </button>
          <button @click="changeData('MONTH', 1, 2, 11)" :class="['custom-button', { active: CheckButton6 ===2 }]">
            月新增
          </button>
        </div>
        <div class="button-right" style="top: 17%">
          <button @click="changeData('DAY', 1, 3, 11)" :class="['custom-button', { active: CheckButton6_1 === 3 }]">
            验机总设备数
          </button>
          <button @click="changeData('DAY', 1, 4, 12)" :class="['custom-button', { active: CheckButton6_1 === 4 }]">
           验机新增设备数
          </button>
          <button @click="changeData('DAY', 1, 5, 13)" :class="['custom-button', { active: CheckButton6_1 === 5 }]">
            验机设备激活数
          </button>
        </div>
        <div ref="chartContainer1_1" style="width: 100%; height: 400px"></div>
      </div>
      <div style="
          position: relative;
          width: 100%;
          height: 400px;
          margin-bottom: 5%;
        ">
        <div style="text-align: center; margin-bottom: 2px">
          <button @click="changeData('DAY', 3, 0, 2)" :class="['custom-button', { active: CheckButton3 === 0 }]">
            日订单
          </button>
          <button @click="changeData('WEEK', 3, 1, 2)" :class="['custom-button', { active: CheckButton3 === 1 }]">
            周订单
          </button>
          <button @click="changeData('MONTH', 3, 2, 2)" :class="['custom-button', { active: CheckButton3 === 2 }]">
            月订单
          </button>
        </div>
        <div ref="chartContainer2" style="width: 100%; height: 100%"></div>
        <div class="button-right">
          <button @click="changeData('DAY', 3, 3, 2)" :class="['custom-button', { active: CheckButton3_1 === 3 }]">
            验机订单
          </button>
          <button @click="changeData('DAY', 3, 4, 3)" :class="['custom-button', { active: CheckButton3_1 === 4 }]">
            验机退款订单
          </button>
          <button @click="changeData('DAY', 3, 5, 2)" :class="['custom-button', { active: CheckButton3_1 === 5 }]">
            验机请求数
          </button>
          <button @click="changeData('DAY', 3, 6, 3)" :class="['custom-button', { active: CheckButton3_1 === 6 }]">
            验机总数
          </button>
        </div>
      </div>

      <div style="text-align: center; margin-bottom: 2px">
        <button @click="changeData('DAY', 4, 0, 4)" :class="['custom-button', { active: CheckButton4 === 0 }]">
          日订单
        </button>
        <button @click="changeData('WEEK', 4, 1, 4)" :class="['custom-button', { active: CheckButton4 === 1 }]">
          周订单
        </button>
        <button @click="changeData('MONTH', 4, 2, 4)" :class="['custom-button', { active: CheckButton4 === 2 }]">
          月订单
        </button>
        <!-- <button
          @click="changeData('TOTAL', 3, 3)"
          :class="['custom-button', { active: CheckButton4 === 3 }]"
        >
          总订单
        </button> -->
      </div>
      <div style="position: relative; width: 100%; height: 400px">
        <div ref="chartContainer3" style="width: 100%; height: 100%"></div>
        <div class="button-right" style="top: 8%;"> 
          <button @click="changeData('DAY', 4, 3, 4)" :class="['custom-button', { active: CheckButton4_1 === 3 }]">
            清监管订单
          </button>
          <button @click="changeData('DAY', 4, 4, 5)" :class="['custom-button', { active: CheckButton4_1 === 4 }]">
            清监管退款订单
          </button>
          <!-- <button
            @click="changeData('DAY', 4, 5, 11)"
            :class="['custom-button', { active: CheckButton4_1 === 5 }]"
          >
            清监管订单(越过)
          </button> -->
          <!-- <button
            @click="changeData('DAY', 4, 6, 12)"
            :class="['custom-button', { active: CheckButton4_1 === 6 }]"
          >
            清监管退款订单(越过)
          </button> -->
        </div>
      </div>
    </div>

    <div class="charts-container">
      <div class="chart-row">
        <div ref="chartContainer4" style="width: 48%; height: 400px"></div>
        <div ref="chartContainer5" style="width: 48%; height: 400px"></div>
      </div>
      <div class="chart-row">
        <div ref="chartContainer6" style="width: 48%; height: 400px"></div>

        <div style="position: relative; width: 48%; height: 400px">
          <div ref="chartContainer7" style="width: 100%; height: 100%"></div>
          <div class="button-right">
            <button @click="changeData('DAY', 8, 0, 8)" :class="['custom-button', { active: CheckButton5 === 0 }]">
              收入总额
            </button>
            <button @click="changeData('DAY', 8, 1, 9)" :class="['custom-button', { active: CheckButton5 === 1 }]">
              验机利润总额
            </button>
          </div>
        </div>
      </div>
      <!-- 暂时不要 -->
      <!-- <div class="chart-row">
        <div ref="chartContainer8" style="width: 48%; height: 400px"></div>
        <div ref="chartContainer9" style="width: 48%; height: 400px"></div>
      </div>
      <div class="chart-row">
        <div ref="chartContainer10" style="width: 48%; height: 400px"></div>
      </div> -->
    </div>
  </div>
</template>

<script>
import { queryReport } from "@/api/system/dataStatistics";
import * as echarts from "echarts";
import "echarts-gl"; // 引入 echarts-gl 扩展包

export default {
  data() {
    return {
      CheckButton1: 0, // 当前选中的按钮索引
      CheckButton2: 0,
      CheckButton3: 0,
      CheckButton4: 0,
      CheckButton6_1:3,
      CheckButton3_1: 3,
      CheckButton4_1: 3,
      CheckButton5: 0,
      CheckButton6: 0, // 当前选中的按钮索引

      TimePeriod: {
        DAY: "DAY",
        WEEK: "WEEK",
        MONTH: "MONTH",
        TOTAL: "TOTAL",
      },

      charts: [],
      categoryDataSets: {
        counts: [],
        daySections: [],
      },
      pieData: {
        type: "pie",
        data: [
          {
            value: 335,
            name: "Windows 11",
          },
          {
            value: 234,
            name: "Windows 10",
          },
          {
            value: 1548,
            name: "mac",
          },
          {
            value: 1548,
            name: "linux",
          },
        ],
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      window.addEventListener("resize", this.handleResize);
    });
  },
  beforeDestroy() {
    this.charts.forEach((chart) => chart?.dispose());
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    openMap() {
      window.location.href = "map";
    },
    initCharts() {
      const chart1 = echarts.init(this.$refs.chartContainer);
      this.charts.push(chart1);
      this.setChartData("DAY", 0, "用户活跃度", 0, 0);

      const chart1_1 = echarts.init(this.$refs.chartContainer1_1);
      this.charts.push(chart1_1);
      this.setChartData("DAY", 1, "普通验机量", 0, 11);

      const chart2 = echarts.init(this.$refs.chartContainer1);
      this.charts.push(chart2);
      this.setChartData("DAY", 2, "新增用户量", 0, 1);

      const chart3 = echarts.init(this.$refs.chartContainer2);
      this.charts.push(chart3);
      this.setChartData("DAY", 3, "专业验机", 0, 2);

      const chart4 = echarts.init(this.$refs.chartContainer3);
      this.charts.push(chart4);
      this.setChartData("DAY", 4, "", 3, 4);

      const chart5 = echarts.init(this.$refs.chartContainer4);
      this.charts.push(chart5);
      this.setChartData("DAY", 5, "专业验机订单成功率", 0, 6);

      const chart6 = echarts.init(this.$refs.chartContainer5);
      this.charts.push(chart6);
      this.setChartData("DAY", 6, "专业验机订单点击验机率", 0, 7);

      const chart7 = echarts.init(this.$refs.chartContainer6);
      this.charts.push(chart7);
      this.setChartData("DAY", 7, "操作系统分布", 1, 10);

      const chart8 = echarts.init(this.$refs.chartContainer7);
      this.charts.push(chart8);
      this.setChartData("DAY", 8, "", 0, 8);

      // const chart9 = echarts.init(this.$refs.chartContainer8);
      // this.charts.push(chart9);
      // this.setChartData("DAY", 8, "专业验机率", 0, 8);

      // const chart10 = echarts.init(this.$refs.chartContainer9);
      // this.charts.push(chart10);
      // this.setChartData("DAY", 9, "操作系统分布", 1, 10);

      // const chart11 = echarts.init(this.$refs.chartContainer10);
      // this.charts.push(chart11);
      // this.setChartData("DAY", 10, "验机设备分布", 2, 10);
    },

    async setChartData(period, chartIndex, text, type, TimePeriodId) {
      //获取数据
      const res = await this.getChartData(period, TimePeriodId);
      const chart = this.charts[chartIndex];
      //替换数据
      if (chart) {
        let data = null;
        const category = res.daySections || null;
        if (chartIndex == 6 || chartIndex == 5) {
          data = res.percentums;
        } else {
          data = res.counts;
        }

        // 获取日数据;
        if (chartIndex != 7) {
          let tooltipOption = {
            trigger: "axis", // 激活整个轴的提示
            axisPointer: {
              type: "line", // 使用直线指示器
              lineStyle: {
                color: "#6a7985", // 指示器的颜色
                width: 1,
              },
            },
          };
          // 只有在 chartIndex 为 4 或 5 时，才为 tooltip 配置 formatter
          if (chartIndex == 5 || chartIndex == 6) {
            tooltipOption.formatter = function (params) {
              if (!params || params.length === 0) return ""; // 防止 params 为空时出错

              const dataIndex = params[0].dataIndex;
              const successRate =
                res && res.percentums && res.percentums[dataIndex] !== undefined
                  ? res.percentums[dataIndex]
                  : 0; // 确保数据有效
              const successOrders =
                res && res.dividends && res.dividends[dataIndex] !== undefined
                  ? res.dividends[dataIndex]
                  : 0; // 确保 dividends 有值
              const totalOrders =
                res && res.divisors && res.divisors[dataIndex] !== undefined
                  ? res.divisors[dataIndex]
                  : 0; // 确保 divisors 有值

              // 格式化提示框内容
              return `
      <div>
        <strong>${category[dataIndex]}</strong><br />
        <strong>成功率：</strong>${successRate}%<br />
        <strong>成功订单数：</strong>${successOrders}<br />
        <strong>总订单数：</strong>${totalOrders}
      </div>
    `;
            };
          } else if (chartIndex == 8) {
            data.forEach((item, index, array) => {
              array[index] = item / 100; // 将每个元素除以100
            });
          }

          chart.setOption({
            grid: {
              left: "5%",
              right: "5%",
              bottom: "5%",
              top: "22%",
              containLabel: true,
            },
            title: {
              text: `${text} `,
              top: "0%",
              left: "5%",
            },
            xAxis: {
              type: "category",
              data: category || [], // 确保 category 不为空
            },
            yAxis: {
              type: "value",
            },
            tooltip: tooltipOption, // 使用条件化的 tooltip 配置
            series: [
              {
                data: data || [], // 确保 data 不为空
                type: "line",
              },
            ],
          });
        } else if (chartIndex === 7) {
          // 将数据转换为 ECharts 支持的格式
          const formattedData = res.item.map((item) => ({
            value: item.count,
            name: item.name,
          }));

          chart.setOption({
            series: [
              {
                type: "pie",
                data: formattedData,
                roseType: "",
                label: {
                  show: true, // 显示标签
                  formatter: "{b}: {d}%", // 显示名称和百分比
                },
              },
            ],
          });
        } else if (type == 2) {
          //获取月数据
          chart.setOption({
            series: [
              {
                type: "pie",
                data: data,
                roseType: "area",
              },
            ],
          });
        }
      }
    },

    changeData(period, chartIndex, buttonIndex, TimePeriodId) {
      if (chartIndex == 0) {
        this.CheckButton1 = buttonIndex;
        this.setChartData(
          period,
          chartIndex,
          "用户活跃度",
          buttonIndex,
          TimePeriodId
        );
      } else if (chartIndex == 1) {
        alert('d')
        if (buttonIndex >= 3) {
          this.CheckButton6 = 0;
          this.CheckButton6_1 = buttonIndex;
        } else {
          this.CheckButton6 = buttonIndex;
        }
        this.setChartData(
          period,
          chartIndex,
          "普通验机量",
          buttonIndex,
          TimePeriodId
        );
        // this.CheckButton6 = buttonIndex;

      } else if (chartIndex == 2) {
        this.setChartData(
          period,
          chartIndex,
          "新增用户量",
          buttonIndex,
          TimePeriodId
        );
        this.CheckButton2 = buttonIndex;
      } else if (chartIndex == 3) {
        if (buttonIndex >= 3) {
          this.CheckButton3 = 0;
          this.CheckButton3_1 = buttonIndex;
        } else {
          this.CheckButton3 = buttonIndex;
        }
        this.setChartData(period, chartIndex, "", buttonIndex, TimePeriodId);
      } else if (chartIndex == 4) {
        if (buttonIndex >= 3) {
          this.CheckButton4 = 0;
          this.CheckButton4_1 = buttonIndex;
        } else {
          this.CheckButton4 = buttonIndex;
        }
        this.setChartData(period, chartIndex, "", buttonIndex, TimePeriodId);
      } else if (chartIndex == 5) {
        this.setChartData(period, chartIndex, "", buttonIndex, TimePeriodId);
      } else if (chartIndex == 8) {
        this.CheckButton5 = buttonIndex;
        this.setChartData(period, chartIndex, "", buttonIndex, TimePeriodId);
      } else if (chartIndex == 7) {
        this.CheckButton5 = buttonIndex;
        if (buttonIndex == 1) {
          chartIndex = 8;
        }
        this.setChartData(period, chartIndex, "", buttonIndex);
      }
    },

    handleResize() {
      this.charts.forEach((chart) => chart?.resize());
    },
    // 使用 async/await 来改进代码
    async getChartData(period, type) {
      const query = { period: period, type: type };
      try {
        // 等待 queryReport 返回的 Promise 结果
        const res = await queryReport(query);

        // 检查响应结果
        if (res.code == 200 && res.data.code == 0) {
          return res.data.data; // 返回获取的数据
        } else {
          throw new Error("数据获取失败，响应状态不正确");
        }
      } catch (error) {
        console.error("请求失败:", error);
        throw error; // 抛出错误，方便外部捕获
      }
    },
  },
};
</script>

<style>
.custom-button {
  background-color: white;
  margin-right: 8px;
  padding: 10px 15px;
  border: 1px solid #090909;
  cursor: pointer;
  color: #090909;
  transition: background-color 0.3s ease;
}

.custom-button:hover {
  background-color: #f0f0f0;
}

/* 添加选中按钮的样式 */
.custom-button.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

/* 按钮定位样式 */
.button-right {
  position: absolute;
  left: 5%;
  top: 17%;
  display: flex;
  gap: 10px;
  z-index: 99;
}

/* 按钮定位样式 */
.hand-button-right {
  position: absolute;
  left: 7vh;
  top: 3vh;
  /* display: flex; */
}

/* 图表容器排版 */
.charts-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 0 3%;
  margin-top: 3%;
}

.chart-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.chart-row>div {
  width: 48%;
  /* 每个图表占据一行的50%，留出间距 */
  height: 400px;
}
</style>
